package com.cicadamob.contact.api.group.asynctask;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.os.Handler;

import com.cicadamob.contact.api.Utils.ImageUtil;
import com.cicadamob.contact.api.Utils.StringUtil;
import com.cicadamob.contact.api.Utils.NetWork.NetWorkUtil;
import com.cicadamob.contact.api.group.bean.Group;
import com.cicadamob.contact.api.group.bean.ResultModel;
import com.cicadamob.contact.api.group.dao.Group_Db_Dao;
import com.cicadamob.contact.api.group.http.Http_Group_Util;
import com.cicadamob.contact.api.group.http.JsonParseUtil;
import com.cicadamob.contact.api.service.Contact;
import com.cicadamob.contact.api.service.ServerUrl;
import com.cicadamob.contact.api.service.AppDbHelper.TS_DATA_VERSION;
import com.lidroid.xutils.exception.HttpException;
/**
 * 添加群组
 * @author 
 *
 */
public class AddGroupZipRequetRunnable implements Runnable{
	private Handler mHandler;
	private int what;
	private Context context;
	private String groupName;
	private String groupImagePath;
	private List<Contact> contactsForAdd;

	private Group_Db_Dao db_dao;
	
	private HttpURLConnection httpURLConnectioncon=null;
	
	/**
	 * 创建群组
	 * @param mHandler
	 * @param what  handler what
	 * @param context
	 * @param groupName  群组名称
	 * @param groupImagePath  群组头像
	 * @param contactsForAdd  成员列表
	 * @param httpURLConnectioncon  预先建立的con
	 */
	public AddGroupZipRequetRunnable(Handler mHandler, int what, Context context,
			String groupName, String groupImagePath,List<Contact> contactsForAdd,HttpURLConnection httpURLConnectioncon) {
		super();
		this.mHandler = mHandler;
		this.what = what;
		this.context = context;
		this.groupName = groupName;
		this.groupImagePath = groupImagePath;
		db_dao=Group_Db_Dao.getInstance(context);
		this.contactsForAdd=contactsForAdd;
	 	this.httpURLConnectioncon=httpURLConnectioncon;
	}
	/**
	 * 创建群组
	 * @param mHandler
	 * @param what  handler what
	 * @param context
	 * @param groupName  群组名称
	 * @param groupImagePath  群组头像
	 * @param contactsForAdd  成员列表
	 */
	public AddGroupZipRequetRunnable(Handler mHandler, int what, Context context,
			String groupName, String groupImagePath,List<Contact> contactsForAdd) {
		super();
		this.mHandler = mHandler;
		this.what = what;
		this.context = context;
		this.groupName = groupName;
		this.groupImagePath = groupImagePath;
		db_dao=Group_Db_Dao.getInstance(context);
		this.contactsForAdd=contactsForAdd;
		
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		ResultModel resultMode = new ResultModel();
		if (!NetWorkUtil.isConnected(context)) {
			resultMode.setRetcode(100);
			sendMessage(resultMode);
			return;// 网络异常
		}

		// TODO Auto-generated method stub
		String result = null;
		String imageInfo = "";
		if (!StringUtil.isEmpty(groupImagePath)) {
			imageInfo = ImageUtil.ImageToBase64Str(groupImagePath);
		}
		try {
			if(httpURLConnectioncon!=null){
				result = Http_Group_Util.postCreateGroup(
						Http_Group_Util.get_createPersonalGroupXML(
								groupName, "",
								JsonParseUtil.contactsTOjson(contactsForAdd), imageInfo),
						ServerUrl.CREATE_GROUP_zip, httpURLConnectioncon);
			}else{
				result=Http_Group_Util.postXML(Http_Group_Util.get_createPersonalGroupXML(
						groupName, "",
						JsonParseUtil.contactsTOjson(contactsForAdd), imageInfo), ServerUrl.CREATE_GROUP_zip);
			}
			
		} catch (SocketTimeoutException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			doFailure(null, null);
		
			return;
		} catch (IOException e) {
			// TODO Auto-generated catch block
	       doFailure(null, null);
			return;
		}

		if (result == null) {
			doFailure(null, null);
			return;
		}
	 
		doSuccess(result);

	}
	
	private void sendMessage(ResultModel resultModel){
		mHandler.obtainMessage(what, resultModel).sendToTarget();
	}
	/**
	 * 处理请求成功
	 * @param result
	 */
	private void doSuccess(String result){
		ResultModel resultmodel = Http_Group_Util.parseResult(result);
		if (resultmodel.getRetcode() == 6 || resultmodel.getRetcode() == 0) {// 6 有重复成员
			ResultModel getGroupResult = getAllGroup(db_dao);
			if (getGroupResult.getRetcode() != 0) {
				resultmodel.setRetcode(101);
				sendMessage(resultmodel);
			} else {
				sendMessage(resultmodel);
			}

		} else if (resultmodel.getRetcode() != 0) {
			sendMessage(resultmodel);
		}
	}
	
	/**
	 * 处理请求失败
	 * @param error
	 * @param msg
	 */
	private void doFailure(HttpException error, String msg){
		ResultModel resultMode = new ResultModel();
		resultMode.setRetcode(-9);
		sendMessage(resultMode);
	}
	
	/**
	 * 获取全部群组
	 */
	public ResultModel getAllGroup(Group_Db_Dao db_dao) {
		ResultModel resultmodel = new ResultModel();
		String result = null;
		String xmlStr = Http_Group_Util.get_GroupAndMemberXML(db_dao
				.getQueryGroupAndMemberTimeStamp());
		try {
			result = Http_Group_Util.postZipXML(xmlStr,
					ServerUrl.GET_GROUP_AND_MEMBER);
			resultmodel = Http_Group_Util.parseResult(result);
			if (resultmodel.getRetcode() == 0) {
				List<String> olderids = db_dao.queryOlderGroupIds();
				String groupSqlStr = resultmodel.getGrouplist();
				String memberSqlStr = resultmodel.getGroupmembers();
				List<String> sqlList = new ArrayList<String>();
				if (!StringUtil.isEmpty(groupSqlStr)) {
					sqlList.addAll(JsonParseUtil
							.jsonTOStringGroupList(groupSqlStr));
				}
				if (!StringUtil.isEmpty(memberSqlStr)) {
					sqlList.addAll(JsonParseUtil
							.jsonTOStringMemberList(memberSqlStr));
				}
				if (sqlList.size() > 0) {
					db_dao.executesql(sqlList);
				}
				
				if (!StringUtil.isEmpty(groupSqlStr)) {
					try {
						JSONObject obj = new JSONObject(groupSqlStr);
						JSONArray ids=obj.optJSONArray("groupInfo");
						Group_Db_Dao groupDao=Group_Db_Dao.getInstance(context);
						ContentValues values=new ContentValues();
						for (int i = 0; i < ids.length(); i++) {
							JSONObject item=ids.getJSONObject(i);
							String groupId=item.getString("groupId");
							String assetId=item.getString("assetId");	
							
							values.put("assetId", assetId);
							groupDao.updateGroupById(values, groupId);
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
				String lastupdatetime = resultmodel.getLastupdatetime();
				if (olderids.size() == 0) {
					db_dao.delGroupVersion();
				}

				db_dao.updateVersion(TS_DATA_VERSION.GROUP_LIST_ID,
						lastupdatetime);
				db_dao.updateVersion(TS_DATA_VERSION.GROUP_LIST_AND_MEMBER,
						lastupdatetime);
				List<Group> groups = db_dao.queryAllGroup();
				for (Group group : groups) {
					if (olderids.size() == 0) {
						db_dao.updateVersion(group.getGroup_id(),
								lastupdatetime);
					}

					if (olderids.size() > 0
							&& !olderids.contains(group.getGroup_id())) {
						db_dao.updateGroupStateById(group.getGroup_id(), 1);
					}
				}
				if (olderids.size() == 0) {
					db_dao.updateAllGroupState();
				}
				if (olderids.size() > 0) {
					for (String groupid : olderids) {
						db_dao.updateVersionNoCreate(groupid, lastupdatetime);
					}
				}
			}
		} catch (SocketTimeoutException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resultmodel.setRetcode(-9);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			resultmodel.setRetcode(-8);
			e.printStackTrace();
		}
		return resultmodel;
	
	}
			
}
